/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef _DAL_DMABUFHEAP_MANAGER_
#define _DAL_DMABUFHEAP_MANAGER_

#include <atomic>
#include <string>
#include <cstdint>

namespace dal_dmabufheap {

class DmaBufHeapManager
{
public:
    struct Block
    {
        void* ptr = nullptr;
        uint32_t size = 0;
        int dmabuf_fd = -1;
        int global_fd = -1;
    };

public:
    DmaBufHeapManager(DmaBufHeapManager& other) = delete;
    void operator=(const DmaBufHeapManager&) = delete;
    static DmaBufHeapManager* GetInstance();

    bool CreateBlock(uint32_t size, Block* block);
    bool GetMappedBlock(Block* block);
    bool ResizeBlock(uint32_t size, Block* block);
    bool DestroyBlock(Block* block);
    bool WriteAndSyncBlock(Block* block, uint32_t pos, void* data, uint32_t size);
    bool SyncAndReadBlock(Block* block, uint32_t pos, void* data, uint32_t size);
    bool SyncBlockReadMode(Block* block);
    bool SyncBlockWriteMode(Block* block);

    const std::string device_path_ = "ipc";

private:
    DmaBufHeapManager();
    ~DmaBufHeapManager();
    static DmaBufHeapManager* instance_;

private:
    std::atomic<bool> is_work_;  // if there is no device, don't work.
    int heap_fd_;
};

}  // namespace dal_dmabufheap

#endif  // _DAL_DMABUFHEAP_MANAGER_